package qhy_chat_websocket.service.impl;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import qhy_chat_websocket.service.WebSocketService;

/**
 * @author qiuhongyu
 * @date 2021/1/26 16:13
 */
@Component
public class ScoketClient implements WebSocketService {

    private static Logger logger = LoggerFactory.getLogger(WebSocketService.class);

    @Autowired
    private WebSocketClient webSocketClient;

    /**
     * 群发
     *
     * @param message
     */
    @Override
    public void groupSending(String message) {

        //这里需要获取状态等待，如果没有这个等待的代码会报连接异常的错误
        while (!webSocketClient.getReadyState().equals(WebSocket.READYSTATE.OPEN)) {
            logger.debug("连接中···请稍后");
        }
        webSocketClient.send(message + "---6666");
    }

    /**
     * 指定发送
     *
     * @param name
     * @param message
     */
    @Override
    public void appointSending(String name, String message) {
        // 这里指定发送的规则由服务端决定参数格式
        webSocketClient.send("TOUSER" + name + ";" + message);
    }
}
